#define CURL_STATICLIB
#include "cybertron/core/UtilCurl.hpp"
#include <curl/curl.h>
#include <string.h>
CYBERTRON_BEGIN
UtilCurl::UtilCurl()
{
}

UtilCurl::~UtilCurl()
{
}

size_t receive_data(void * contents, size_t size, size_t nmemb, void * stream)
{
	string *str = (string*)stream;
	(*str).append((char*)contents, size*nmemb);
	return size * nmemb;
}

CybertronCoreAPI int UtilCurl::HttpGet(const std::string & strUrl, std::string & strResponse, std::vector<std::string>headerString, int nTimeout)
{
	CURLcode res;
	CURL* pCURL = curl_easy_init();
	struct curl_slist* headers = NULL;
	if (pCURL == NULL) {
		return CURLE_FAILED_INIT;
	}

	curl_easy_setopt(pCURL, CURLOPT_HTTPHEADER, headers);
	//headers = curl_slist_append(headers, "content-type:application/json");
	for (std::vector<std::string>::iterator it = headerString.begin(); it < headerString.end(); it++) {
		headers = curl_slist_append(headers, it->c_str());
	}
	//headers = curl_slist_append(headers, headerString.c_str());
	curl_easy_setopt(pCURL, CURLOPT_HTTPHEADER, headers);

	curl_easy_setopt(pCURL, CURLOPT_URL, strUrl.c_str());
	curl_easy_setopt(pCURL, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(pCURL, CURLOPT_TIMEOUT, nTimeout);
	curl_easy_setopt(pCURL, CURLOPT_NOPROGRESS, 1L);
	curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, receive_data);
	curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, (void*)&strResponse);
	res = curl_easy_perform(pCURL);
	curl_easy_cleanup(pCURL);
	return res;
}

CybertronCoreAPI int UtilCurl::HttpPost(const std::string & strUrl, std::string strBody, std::string & strResponse, std::vector<std::string>headerString, int nTimeout)
{
	CURLcode res;
	char szJsonData[1024];
	memset(szJsonData, 0, sizeof(szJsonData));
	strcpy(szJsonData, strBody.c_str());
	CURL* pCURL = curl_easy_init();
	struct curl_slist* headers = NULL;
	if (pCURL == NULL) {
		return CURLE_FAILED_INIT;
	}

	CURLcode ret;
	ret = curl_easy_setopt(pCURL, CURLOPT_URL, strUrl.c_str());

	ret = curl_easy_setopt(pCURL, CURLOPT_POST, 1L);
	for (std::vector<std::string>::iterator it = headerString.begin(); it < headerString.end(); it++) {
		headers = curl_slist_append(headers, it->c_str());
	}
	//headers = curl_slist_append(headers, "content-type:application/json");
	ret = curl_easy_setopt(pCURL, CURLOPT_HTTPHEADER, headers);
	ret = curl_easy_setopt(pCURL, CURLOPT_POSTFIELDS, szJsonData);
	ret = curl_easy_setopt(pCURL, CURLOPT_TIMEOUT, nTimeout);
	ret = curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, receive_data);
	ret = curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, (void*)&strResponse);

	res = curl_easy_perform(pCURL);
	curl_easy_cleanup(pCURL);
	return res;
}
CYBERTRON_END